// import Getmd5 from 'js-md5';

import {uploadCheckAxios,uploadChunkAxios,mergeFileAxios} from '../api/autopay'
import Getmd5 from 'js-md5';

export const uploadByPieces = ({ file,descmsg,fileMD5, pieceSize = 2,progress, success, error,Count ,Chunknum}) => {
  // if (!file || !file.length) return
  // 上传过程中用到的变量
  // let fileMD5 = ''// 总文件列表
  const chunkSize = pieceSize * 1024 * 1024 // 5MB一片
  const chunkCount = Math.ceil(file.size / chunkSize) // 总片数
  Count &&  Count(chunkCount) 
  console.log(file);
  // 获取md5
  const readFileMD5 = () => {
    // 读取视频文件的md5
      // let fileRederInstance = new FileReader()

      // fileRederInstance.readAsBinaryString(file)
      // console.log("read file");
      // console.log(file);
      // fileRederInstance.addEventListener('load', e => {
      // console.log("load file");
      // let fileBolb = e.target.result
      // console.log(3);
      // fileMD5 = Getmd5(fileBolb);
      // console.log("md5=",fileMD5);
      uploadCheckAxios({ "md5": fileMD5 }).then(res => {
        if (res.code == 200) {
          console.log("文件已被上传")
          console.log(res.data)
          // success && success(res)
        }
        else { 
          console.log("文件未被上传，将分片上传")
          readChunkMD5() 
        }
      }).catch(
        function (e) {
          console.log("文件合并错误")
          console.log(e)
        }
      )

      // })
  }
  const getChunkInfo = (file, currentChunk, chunkSize) => {
    let start = currentChunk * chunkSize
    let end = Math.min(file.size, start + chunkSize)
    let chunk = file.slice(start, end)
    // console.log(start, end, chunk);
    return { start, end, chunk }
  }
  // 针对每个文件进行chunk处理
  const readChunkMD5 = () => {
    // 针对单个文件进行chunk上传
    for (var i = 0; i < chunkCount; i++) {
      const { chunk } = getChunkInfo(file, i, chunkSize)
      // console.log("总片数"+chunkCount)
      // console.log("分片后的数据---测试："+i)
      uploadChunk({ chunk, currentChunk: i, chunkCount })
    }
  }
  const uploadChunk = (chunkInfo) => {
    // progressFun()
    let fetchForm = new FormData()
    fetchForm.append('chunk', chunkInfo.currentChunk)
    fetchForm.append('chunkSize', chunkSize)
    fetchForm.append('chunks', chunkInfo.chunkCount)
    fetchForm.append('file', chunkInfo.chunk)
    fetchForm.append('md5', fileMD5)
    fetchForm.append('msg', descmsg)
    fetchForm.append('name', file.name)
    
    uploadChunkAxios(fetchForm).then(res => {
      if (res.code == 200) {
        Chunknum &&Chunknum(chunkInfo.currentChunk)
        if (chunkInfo.currentChunk < chunkInfo.chunkCount - 1) {
          console.log("分片全部上传成功")
        } else {
          // 当总数大于等于分片个数的时候
          if (chunkInfo.currentChunk >= chunkInfo.chunkCount - 1) {
            console.log("文件开始合并")
            mergeFileAxios({ "md5": fileMD5, "name": file.name,"msg":descmsg,"num":chunkInfo.chunkCount,"size":file.size }).then(res => {
              if (res.code == 200) {
                console.log("文件合并成功")
                success && success(res.data)
                this.fileMD5 = ''
              }else { console.log(res.data.msg) }
             }).catch((e) => {
               console.log("文件合并错误")
             })
          }
        }
      }
      else {
        console.log(res.msg)
      }
    }).catch((e) => {
      error && error(e)
    })
  }
  readFileMD5() // 开始执行代码
}